const http = require('http');
const Q = require('q');
const EventEmitter = require('events');
const emitter = new EventEmitter();
exports.findList = getDataByPageIndex;
exports.emitter = emitter;
var list = [];

function getDataByPageIndex(pageIndex) {

    const url = 'http://www.anluyun1688.com//DbHelper/SearchProduct?PageIndex=' + pageIndex + '&timestamp=' + new Date().getTime();

    http.get(url, (res) => {
        const { statusCode } = res;
        const contentType = res.headers['content-type'];

        let error;
        if (statusCode !== 200) {
            error = new Error('Request Failed.\n' +
                `Status Code: ${statusCode}`);
        } else if (!/^application\/json/.test(contentType)) {
            error = new Error('Invalid content-type.\n' +
                `Expected application/json but received ${contentType}`);
        }
        if (error) {
            console.error(error.message);
            // consume response data to free up memory
            res.resume();
            return;
        }

        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => { rawData += chunk; });
        res.on('end', () => {
            try {
                const parsedData = JSON.parse(JSON.parse(rawData));

                var pageCount = parsedData.PageCount;
                var pageindex = parsedData.PageIndex;
                // console.log(pageCount + '    ' + pageindex);
                //数据加载完成
                for (var dili of parsedData.plist) {

                    list.push(dili.ID);
                }
                if (pageindex < pageCount) {


                    getDataByPageIndex(pageIndex + 1);
                } else {

                    console.log(list);
                    emitter.emit('dataLoadFinished', list);
                }

            } catch (e) {
                console.error(e.message);
            }
        });
    }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
    });
    return list;
}